#include "listform.h"
#include "qdebug.h"
#include "qfileinfo.h"
#include "qsqlerror.h"
#include <QMimeDatabase>

listForm::listForm() {}

void listForm::getMusicByUrl(QList<QUrl> urList)
{
    //添加所有源
    for(const auto &url : urList)
    {
        QString mpath = url.toLocalFile();
        if(musicPath.contains(mpath))
            continue;
        musicPath.insert(mpath);
        //确认文件有效
        QMimeDatabase mimeDB;
        QFileInfo file = url.toLocalFile();
        QMimeType type = mimeDB.mimeTypeForFile(file, QMimeDatabase::MatchExtension);
        // qDebug() << type;
        QString data = type.name();
        // qDebug() << data;

        if(data == "audio/mpeg" || data == "audio/flac" || data == "audio/ogg")
        {
            //创建对象添加
            listFormitem musicitem(url);
            musicitem.praseMusicitem(url);
            musiclist.push_back(musicitem);
            qDebug() << musicitem.getAlbumitem();
        }
    }
}

QVector<listFormitem> &listForm::getMusicList()
{
    return musiclist;
}

iterator listForm::getMusicId(const QString &pageid)
{
    for(auto e = musiclist.begin(); e != musiclist.end(); ++e)
    {
        if(e->getitemId() == pageid)
        {
            return e;
        }
    }
    return musiclist.end();
}

iterator listForm::begin()
{
    return musiclist.begin();
}

iterator listForm::end()
{
    return musiclist.end();
}

size_t listForm::size()
{
    return musiclist.size();
}

void listForm::addMusicToDB()
{
    for(auto e : std::as_const(musiclist))
    {
        e.insertMusicFromE();
    }
}

void listForm::getMusicFormBD()
{
    musiclist.clear();
    QSqlQuery query;
    query.prepare("select itemid,name,author,album,duration,itemurl,isLike,isHistory from musiclist");
    if(!query.exec())
    {
        qDebug() << "数据库查询失败" << query.lastError().text();
        return;
    }

    while(query.next())
    {
        listFormitem item;
        item.setitemId(query.value(0).toString());
        item.setNameitem(query.value(1).toString());
        item.setAuthoritem(query.value(2).toString());
        item.setAlbumitem(query.value(3).toString());
        item.setDurationitem(query.value(4).toLongLong());
        item.setUrlitem("file:///"+query.value(5).toString());
        item.setisLikeitem(query.value(6).toBool());
        item.setisHistoryitem(query.value(7).toBool());
        musiclist.push_back(item);
        // qDebug() << item.getAlbumitem();
        musicPath.insert(item.getUrlitem().toLocalFile());
    }
}

